﻿using System;
using System.Windows.Input;
using AIStudio.Wpf.DiagramDesigner.Geometrys;
using AIStudio.Wpf.DiagramDesigner.Models;

namespace AIStudio.Wpf.DiagramDesigner
{
    public class ConnectorVertexModel : ConnectorPointModel
    {
        public ConnectorVertexModel(ConnectionViewModel connector, PointBase? position = null) : this(null, connector, position)
        {
        }

        public ConnectorVertexModel(IDiagramViewModel root, ConnectionViewModel connector, PointBase? position = null) : base(root)
        {
            Parent = connector;
            X = position?.X ?? 0;
            Y = position?.Y ?? 0;
        }

        public ConnectorVertexModel(IDiagramViewModel root, ConnectionViewModel connector, SelectableItemBase designer) : base(root, designer)
        {
            Parent = connector;
        }

        public ConnectorVertexModel(IDiagramViewModel root, ConnectionViewModel connector, SerializableItem serializableItem, string serializableType) : base(root, serializableItem, serializableType)
        {
            Parent = connector;
        }

        public override SelectableItemBase GetSerializableObject()
        {
            return new ConnectorVertexItem(this);
        }

        public override void Init(IDiagramViewModel root, bool initNew)
        {
            base.Init(root, initNew);

            DeleteVertexCommand = new SimpleCommand(Command_Enable, DeleteVertex);
        }

        protected override void LoadDesignerItemViewModel(SelectableItemBase designerbase)
        {
            base.LoadDesignerItemViewModel(designerbase);

            if (designerbase is ConnectorVertexItem designer)
            {
                designer.ConnectorVertexType = designer.ConnectorVertexType;
            }

        }

        public ConnectorVertexType ConnectorVertexType
        {
            get; set;
        }

        public ConnectionViewModel Connector
        {
            get
            {
                return Parent as ConnectionViewModel;
            }
        }

        public override PointBase Position
        {
            get
            {
                return new PointBase(Connector.Area.Left + Left, Connector.Area.Top + Top);
            }
        }

        public override PointBase MiddlePosition => new PointBase(Connector.Area.Left + Left + ConnectorWidth / 2, Connector.Area.Top + Top + ConnectorHeight / 2);

        public ICommand DeleteVertexCommand
        {
            get; set;
        }

        private void DeleteVertex(object parameter)
        {
            if (parameter is ConnectorVertexModel vertice)
            {
                Connector.RemoveVertex(this);
            }
        }
    }

    public enum ConnectorVertexType
    {
        None,
        Start,
        End,
    }
}
